package ribbon;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 负载均衡策略：优先选择与服务调用方在相同集群（比如都在北京集群）
 * 测试方案：分别启动北京集群、南京集群的user-center、然后启动1个北京集群的content-center
 */
@Slf4j
public class MyRibbonRuleSameCluster extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;


    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        try {
            // 获取Ribbon相关API
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();

            // 获取需要调用的服务名
            String serviceName = loadBalancer.getName();

            // 获取服务发现相关API
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

            // 1、获取该服务所有存活的实例
            List<Instance> instances = namingService.selectInstances(serviceName, true);
            if (CollectionUtils.isEmpty(instances)) {
                log.warn("{}服务当前无任何实例", serviceName);
                return null;
            }

            // 2、筛选出与调用方处于相同集群的服务的所有实例
            String clusterName = this.nacosDiscoveryProperties.getClusterName();//服务消费方所在集群的名字
            List<Instance> instancesToChoose = instances;
            if (StringUtils.isNotBlank(clusterName)) {
                List<Instance> sameClusterInstances = instances.stream()
                        .filter(instance -> Objects.equals(clusterName, instance.getClusterName()))//服务消费方、提供方所在集群相同
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(sameClusterInstances)) {
                    instancesToChoose = sameClusterInstances;
                } else {
                    log.warn("发生跨集群的调用，name = {}, clusterName = {}, instance = {}", serviceName, clusterName, instances);
                }
            }

            // 3、通过nacos client的基于权重的负载均衡策略选出1个实例
            Instance instance = NacosUtils.getHostByRandomWeight2(instancesToChoose);
            log.info("所在集群："+clusterName);
            return new NacosServer(instance);
        } catch (NacosException e) {
            log.warn("NacosRule发生异常", e);
            return null;
        }
    }
}
